package com.niannian.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.niannian.MyApplication;
import com.niannian.R;
import com.niannian.util.network.HttpService;
import com.umeng.analytics.MobclickAgent;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

/**
 * 播放管理
 * 
 * @author shenglin
 * 
 */
public class AudioPlayerManager {
	Context ctx;
	private static AudioPlayer player = null;
	BaseAdapter bAdapter;// 来自的适配器

	public int currentPlay = -1;// 当前播放任务是那个模块
	public String currPlayingPath = "";// 当前播放中的语音文件地址名字（这个地址是服务器上的文件地址名字）
	public String currPlayinglocaPath = "";// 当前播放中的语音文件本地地址
	public int isPlayStatus = 0;// 语音播放状态 1表示播放中，2表示暂停,3播放完成
	String playPath = "";// 需要播放的路径(最后一个点击的语音地址)

	LinearLayout ll_voice_progress;
	ImageView btn_play;
	SeekBar sb_voice_volume;
	ImageView btn_play_close;

	// 发布录音
	TextView bt_greeting_voice;
	// 发布评论语音
	Button btn_comment_recording_play;

	String audPath = "";
	public Map<String, String> DownloadingMap = new HashMap<String, String>();// 下载中的语音

	public AudioPlayerManager(Context ctx) {
		this.ctx = ctx;
		player = new AudioPlayer();
		player.mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer arg0) {
				isPlayStatus = 3;
				currPlayinglocaPath = "";
				PlayStatus();
			}
		});
		createFloatView();
		ViewLister();
	}

	WindowManager mWindowManager;
	LinearLayout mFloatLayout;
	WindowManager.LayoutParams wmParams;

	private void createFloatView() {
		wmParams = new WindowManager.LayoutParams();
		// 获取WindowManagerImpl.CompatModeWrapper
		mWindowManager = (WindowManager) ctx.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
		// 设置window type
		wmParams.type = LayoutParams.TYPE_PHONE;
		// 设置图片格式，效果为背景透明
		wmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		wmParams.flags =
		// LayoutParams.FLAG_NOT_TOUCH_MODAL |
		LayoutParams.FLAG_NOT_FOCUSABLE
		// LayoutParams.FLAG_NOT_TOUCHABLE
		;

		// 调整悬浮窗显示的停靠位置为左侧置顶
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;

		// 以屏幕左上角为原点，设置x、y初始值
		wmParams.x = 0;
		wmParams.y = Common.dip2px(ctx, 50);

		/*
		 * // 设置悬浮窗口长宽数据 wmParams.width = 200; wmParams.height = 80;
		 */

		// 设置悬浮窗口长宽数据
		wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
		wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

		LayoutInflater inflater = LayoutInflater.from(ctx.getApplicationContext());
		// 获取浮动窗口视图所在布局
		mFloatLayout = (LinearLayout) inflater.inflate(R.layout.dialog_audio_playe, null);

		ll_voice_progress = (LinearLayout) mFloatLayout.findViewById(R.id.ll_voice_progress);
		btn_play = (ImageView) mFloatLayout.findViewById(R.id.btn_play);
		sb_voice_volume = (SeekBar) mFloatLayout.findViewById(R.id.sb_voice_volume);
		btn_play_close = (ImageView) mFloatLayout.findViewById(R.id.btn_play_close);
		sb_voice_volume.setOnSeekBarChangeListener(new SeekBarChangeEvent());
		// this.sb_voice_volume.setProgress(0);
		player.ShowView(sb_voice_volume, null);

		// 添加mFloatLayout
		mWindowManager.addView(mFloatLayout, wmParams);

		mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
				View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

		mFloatLayout.setVisibility(View.GONE);
	}

	/**
	 * 家庭动态事件
	 */
	public void ViewLister() {
		ll_voice_progress.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		btn_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Player(currPlayinglocaPath);
				PlayStatus();
			}
		});
		btn_play_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				player.mediaPlayer.stop();
				isPlayStatus = 3;
				PlayStatus();
			}
		});

	}

	/**
	 * 播放来自适配器的语音
	 */
	public void aPlayer(BaseAdapter bAdapter, String playPath) {
		if (this.bAdapter != null && this.bAdapter != bAdapter) {
			playerPause();
			this.bAdapter.notifyDataSetChanged();
		}
		this.bAdapter = bAdapter;
		initDownloadVoice(playPath);
	}

	RelativeLayout rl_play;
	ImageView iv_status_play;

	public void FromAudition(RelativeLayout rl_play, ImageView iv_status_play, String audPathf) {
		this.audPath = audPathf;
		this.rl_play = rl_play;
		this.iv_status_play = iv_status_play;
		playerPause();
		this.rl_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Player(audPath);
				PlayStatus();
			}
		});
	}

	public void FromNetAudition(RelativeLayout rl_play, ImageView iv_status_play, final String audPathf) {

		this.rl_play = rl_play;
		this.iv_status_play = iv_status_play;
		initDownloadVoice(audPathf);
		this.rl_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				Player(audPath);
//				PlayStatus();
				initDownloadVoice(audPathf);
			}
		});
	}

	/**
	 * 
	 * @author shenglin
	 * 
	 */

	public void playerPause() {
		
		player.pause();
		isPlayStatus = 3;
		PlayStatus();

	}

	class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
		int progress;

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			// //
			// 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
			// if (fromUser) {
			// this.progress = progress * player.mediaPlayer.getDuration() /
			// seekBar.getMax();
			// player.mediaPlayer.seekTo(this.progress);
			// }
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			player.mediaPlayer.seekTo(seekBar.getProgress());
		}
	}

	/**
	 * 家庭动态播放状态
	 */
	public void PlayStatus() {
		switch (isPlayStatus) {
		case 1:
			mFloatLayout.setVisibility(View.VISIBLE);
			btn_play.setImageResource(R.drawable.player_pause);
			break;
		case 2:
			mFloatLayout.setVisibility(View.VISIBLE);
			btn_play.setImageResource(R.drawable.player_play);
			break;
		case 3:
			mFloatLayout.setVisibility(View.GONE);
			btn_play.setImageResource(R.drawable.player_play);
			player.mediaPlayer.stop();
			currPlayinglocaPath = "";
			break;
		default:
			break;
		}
		if (bAdapter != null) {
			bAdapter.notifyDataSetChanged();
		}

		if (iv_status_play != null) {
			switch (isPlayStatus) {
			case 1:
				iv_status_play.setBackgroundResource(R.drawable.family_status_play_anim);
				AnimationDrawable anim = (AnimationDrawable) iv_status_play.getBackground();
				anim.stop();
				anim.start();
				break;
			case 2:
				iv_status_play.setBackgroundResource(R.drawable.status_pause);
				break;
			case 3:
				iv_status_play.setBackgroundResource(R.drawable.play_3);
				break;
			default:
				break;
			}
		}

	}

	/**
	 * 发送评论试听播放
	 */
	public void PushCommentAudPlayStatus() {
		if (btn_comment_recording_play == null) {
			return;
		}
		switch (isPlayStatus) {
		case 1:
			btn_comment_recording_play.setBackgroundResource(R.drawable.btn_comment_recording_pause_bg);
			break;
		case 2:
			btn_comment_recording_play.setBackgroundResource(R.drawable.btn_comment_recording_play_bg);
			break;
		case 3:
			btn_comment_recording_play.setBackgroundResource(R.drawable.btn_comment_recording_play_bg);
			break;
		default:
			break;
		}

	}

	/**
	 * 初始化 播放那个
	 * 
	 * @param curPlayingType
	 *            当前播放模块
	 */
	private void initPlayer(String locaFilePath) {
		currPlayingPath = playPath;

		Player(locaFilePath);

	}

	private void Player(String locaFilePath) {
		Boolean isFirst = false;
		if (!currPlayinglocaPath.equals(locaFilePath)) {
			isFirst = true;
			isPlayStatus = 3;

			currPlayinglocaPath = locaFilePath;
		} else {
			isFirst = false;
		}
		if (isFirst) {
			isPlayStatus = 1;
			player.playUrl(currPlayinglocaPath);
			player.play();
			MobclickAgent.onEvent(ctx, UmengPage.PLAY_AUD_PRESS);

		} else {
			if (player.mediaPlayer.isPlaying()) {
				isPlayStatus = 2;
				player.pause();
				MobclickAgent.onEvent(ctx, UmengPage.PAUSE_AUD_PRESS);
			} else {
				isPlayStatus = 1;
				player.play();
				MobclickAgent.onEvent(ctx, UmengPage.PLAY_AUD_PRESS);
			}
		}

		PlayStatus();

	}

	/**
	 * 初始化下载
	 * 
	 * @param curPlayingType
	 *            当前播放模块
	 */
	private void initDownloadVoice(String playPath) {
		String uri = Common.getPublicAudioUrl(playPath);// 下载地址
		String locaFilePath = MyApplication.FILE_PATH_AUDIO + Common.md5_3(uri) + ".amr";// 文件保存地址
		this.playPath = playPath;

		// 本地不存在，以及没有在下载列表的时候，开始下载，
		if (!new File(locaFilePath).exists() && !DownloadingMap.containsKey(playPath)) {

			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("uri", uri);
			paramMap.put("locaFilePath", locaFilePath);
			paramMap.put("playPath", playPath);

			DownloadingMap.put(playPath, "");// 加入到下载列表
			new DownloadVoice().init(paramMap).execute();// 开始下载

		} else if (new File(locaFilePath).exists()) {
			initPlayer(locaFilePath);
		} else {
			// 正在下载中...
		}
	}

	/**
	 * 下载语音
	 * 
	 * @author shenglin
	 * 
	 */
	protected class DownloadVoice extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			// Common.tip(FamilyNewsActivity.this, "下载失败");

			String playPath = paramMap.get("playPath").toString();
			DownloadingMap.remove(playPath);

		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				DownloadVoiceSuc(paramMap);
			} else {

				String playPath = paramMap.get("playPath").toString();
				DownloadingMap.remove(playPath);

			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return new HttpService().downLoadFile(paramMap.get("uri").toString(), paramMap.get("locaFilePath").toString());
		}
	}

	/**
	 * 下载成功
	 * 
	 * @param paramMap
	 */
	private void DownloadVoiceSuc(Map<String, Object> paramMap) {
		String playPath = paramMap.get("playPath").toString();
		if (this.playPath == playPath) {
			String locaFilePath = paramMap.get("locaFilePath").toString();
			initPlayer(locaFilePath);
		}
		DownloadingMap.remove(playPath);
	}
}
